const express = require('express')
const router = express.Router()
const multer = require('multer')
const auth = require('../middleware/auth')
const fileService = require('../services/fileService')
const logger = require('../utils/logger')

// 配置文件上传中间件
const upload = multer({
  storage: multer.memoryStorage(),
  limits: {
    fileSize: 50 * 1024 * 1024 // 50MB
  }
})

/**
 * @api {post} /api/files/upload 上传文件
 * @apiDescription 上传文件到服务器
 * @apiName UploadFile
 * @apiGroup Files
 * @apiHeader {String} Authorization 用户token
 * @apiParam {File} file 要上传的文件
 * @apiSuccess {Boolean} success 是否成功
 * @apiSuccess {Object} data 文件信息
 */
router.post('/upload', auth, upload.single('file'), async (req, res) => {
  try {
    if (!req.file) {
      return res.status(400).json({
        success: false,
        message: '未选择文件'
      })
    }

    const userId = req.user.id
    const file = req.file

    // 验证文件类型
    if (!fileService.isFileTypeSupported(file.mimetype)) {
      return res.status(400).json({
        success: false,
        message: '不支持的文件类型'
      })
    }

    const result = await fileService.uploadFile(userId, file)

    res.json({
      success: true,
      message: '文件上传成功',
      data: result
    })
  } catch (error) {
    logger.error('File upload error:', error)
    res.status(500).json({
      success: false,
      message: error.message || '文件上传失败'
    })
  }
})

/**
 * @api {get} /api/files 获取文件列表
 * @apiDescription 获取当前用户的文件列表
 * @apiName GetFiles
 * @apiGroup Files
 * @apiHeader {String} Authorization 用户token
 * @apiParam {Number} page 页码
 * @apiParam {Number} limit 每页数量
 * @apiParam {String} type 文件类型筛选
 * @apiSuccess {Boolean} success 是否成功
 * @apiSuccess {Object} data 文件列表和分页信息
 */
router.get('/', auth, async (req, res) => {
  try {
    const userId = req.user.id
    const page = parseInt(req.query.page) || 1
    const limit = parseInt(req.query.limit) || 20
    const type = req.query.type || 'all'

    // 这里可以根据type参数进行筛选，暂时忽略
    const result = await fileService.getUserFiles(userId, page, limit)

    res.json({
      success: true,
      data: result
    })
  } catch (error) {
    logger.error('Get files error:', error)
    res.status(500).json({
      success: false,
      message: error.message || '获取文件列表失败'
    })
  }
})

/**
 * @api {get} /api/files/:id 获取文件详情
 * @apiDescription 获取指定文件的详细信息
 * @apiName GetFileDetail
 * @apiGroup Files
 * @apiHeader {String} Authorization 用户token
 * @apiParam {Number} id 文件ID
 * @apiSuccess {Boolean} success 是否成功
 * @apiSuccess {Object} data 文件详情
 */
router.get('/:id', auth, async (req, res) => {
  try {
    const userId = req.user.id
    const fileId = parseInt(req.params.id)

    if (!fileId) {
      return res.status(400).json({
        success: false,
        message: '无效的文件ID'
      })
    }

    const fileInfo = await fileService.getFileById(fileId, userId)

    res.json({
      success: true,
      data: fileInfo
    })
  } catch (error) {
    logger.error('Get file detail error:', error)
    res.status(500).json({
      success: false,
      message: error.message || '获取文件详情失败'
    })
  }
})

/**
 * @api {delete} /api/files/:id 删除文件
 * @apiDescription 删除指定文件
 * @apiName DeleteFile
 * @apiGroup Files
 * @apiHeader {String} Authorization 用户token
 * @apiParam {Number} id 文件ID
 * @apiSuccess {Boolean} success 是否成功
 */
router.delete('/:id', auth, async (req, res) => {
  try {
    const userId = req.user.id
    const fileId = parseInt(req.params.id)

    if (!fileId) {
      return res.status(400).json({
        success: false,
        message: '无效的文件ID'
      })
    }

    await fileService.deleteFile(fileId, userId)

    res.json({
      success: true,
      message: '文件删除成功'
    })
  } catch (error) {
    logger.error('Delete file error:', error)
    res.status(500).json({
      success: false,
      message: error.message || '删除文件失败'
    })
  }
})

/**
 * @api {get} /api/files/:id/download 获取文件下载链接
 * @apiDescription 获取指定文件的下载链接
 * @apiName GetFileDownloadUrl
 * @apiGroup Files
 * @apiHeader {String} Authorization 用户token
 * @apiParam {Number} id 文件ID
 * @apiParam {Number} expires 链接有效期(秒)
 * @apiSuccess {Boolean} success 是否成功
 * @apiSuccess {Object} data 下载链接信息
 */
router.get('/:id/download', auth, async (req, res) => {
  try {
    const userId = req.user.id
    const fileId = parseInt(req.params.id)
    const expires = parseInt(req.query.expires) || 3600

    if (!fileId) {
      return res.status(400).json({
        success: false,
        message: '无效的文件ID'
      })
    }

    const downloadUrl = await fileService.getDownloadUrl(fileId, userId, expires)

    res.json({
      success: true,
      data: {
        downloadUrl,
        expires
      }
    })
  } catch (error) {
    logger.error('Get download URL error:', error)
    res.status(500).json({
      success: false,
      message: error.message || '获取下载链接失败'
    })
  }
})

/**
 * @api {post} /api/files/:id/reprocess 重新处理文件
 * @apiDescription 重新处理指定文件(生成预览图等)
 * @apiName ReprocessFile
 * @apiGroup Files
 * @apiHeader {String} Authorization 用户token
 * @apiParam {Number} id 文件ID
 * @apiSuccess {Boolean} success 是否成功
 * @apiSuccess {Object} data 处理结果
 */
router.post('/:id/reprocess', auth, async (req, res) => {
  try {
    const userId = req.user.id
    const fileId = parseInt(req.params.id)

    if (!fileId) {
      return res.status(400).json({
        success: false,
        message: '无效的文件ID'
      })
    }

    const result = await fileService.reprocessFile(fileId, userId)

    res.json({
      success: true,
      message: '文件处理成功',
      data: result
    })
  } catch (error) {
    logger.error('Reprocess file error:', error)
    res.status(500).json({
      success: false,
      message: error.message || '文件处理失败'
    })
  }
})

/**
 * @api {get} /api/files/supported-types 获取支持的文件类型
 * @apiDescription 获取系统支持的文件类型列表
 * @apiName GetSupportedFileTypes
 * @apiGroup Files
 * @apiSuccess {Boolean} success 是否成功
 * @apiSuccess {Object} data 支持的文件类型
 */
router.get('/supported-types', async (req, res) => {
  try {
    // 从配置中获取支持的文件类型
    const { SUPPORTED_FILE_TYPES } = require('../config/oss')
    
    // 将文件类型分类
    const types = {
      documents: [],
      images: [],
      others: []
    }
    
    for (const [mimetype, info] of Object.entries(SUPPORTED_FILE_TYPES)) {
      if (mimetype.startsWith('image/')) {
        types.images.push({ mimetype, ...info })
      } else if (
        mimetype.includes('pdf') || 
        mimetype.includes('word') || 
        mimetype.includes('excel') || 
        mimetype.includes('powerpoint') ||
        mimetype.includes('text')
      ) {
        types.documents.push({ mimetype, ...info })
      } else {
        types.others.push({ mimetype, ...info })
      }
    }
    
    res.json({
      success: true,
      data: types
    })
  } catch (error) {
    logger.error('Get supported file types error:', error)
    res.status(500).json({
      success: false,
      message: '获取支持的文件类型失败'
    })
  }
})

/**
 * @api {post} /api/files/batch-delete 批量删除文件
 * @apiDescription 批量删除文件
 * @apiName BatchDeleteFiles
 * @apiGroup Files
 * @apiHeader {String} Authorization 用户token
 * @apiParam {Array} fileIds 文件ID数组
 * @apiSuccess {Boolean} success 是否成功
 * @apiSuccess {Object} data 删除结果
 */
router.post('/batch-delete', auth, async (req, res) => {
  try {
    const userId = req.user.id
    const { fileIds } = req.body
    
    if (!Array.isArray(fileIds) || fileIds.length === 0) {
      return res.status(400).json({
        success: false,
        message: '无效的文件ID列表'
      })
    }
    
    const results = {
      success: [],
      failed: []
    }
    
    for (const fileId of fileIds) {
      try {
        await fileService.deleteFile(fileId, userId)
        results.success.push(fileId)
      } catch (error) {
        results.failed.push({
          id: fileId,
          error: error.message
        })
      }
    }
    
    res.json({
      success: true,
      message: `成功删除${results.success.length}个文件，失败${results.failed.length}个`,
      data: results
    })
  } catch (error) {
    logger.error('Batch delete files error:', error)
    res.status(500).json({
      success: false,
      message: error.message || '批量删除文件失败'
    })
  }
})

/**
 * @api {get} /api/files/search 搜索文件
 * @apiDescription 搜索文件
 * @apiName SearchFiles
 * @apiGroup Files
 * @apiHeader {String} Authorization 用户token
 * @apiParam {String} keyword 搜索关键词
 * @apiParam {Number} page 页码
 * @apiParam {Number} limit 每页数量
 * @apiSuccess {Boolean} success 是否成功
 * @apiSuccess {Object} data 搜索结果
 */
router.get('/search', auth, async (req, res) => {
  try {
    const userId = req.user.id
    const keyword = req.query.keyword || ''
    const page = parseInt(req.query.page) || 1
    const limit = parseInt(req.query.limit) || 20
    
    // 这里应该调用fileService的搜索方法
    // 暂时简化处理，直接返回用户文件列表
    const result = await fileService.getUserFiles(userId, page, limit)
    
    res.json({
      success: true,
      data: result
    })
  } catch (error) {
    logger.error('Search files error:', error)
    res.status(500).json({
      success: false,
      message: error.message || '搜索文件失败'
    })
  }
})

/**
 * @api {get} /api/files/stats 获取文件统计信息
 * @apiDescription 获取当前用户的文件统计信息
 * @apiName GetFileStats
 * @apiGroup Files
 * @apiHeader {String} Authorization 用户token
 * @apiSuccess {Boolean} success 是否成功
 * @apiSuccess {Object} data 统计信息
 */
router.get('/stats', auth, async (req, res) => {
  try {
    const userId = req.user.id
    
    // 这里应该调用fileService的统计方法
    // 暂时返回模拟数据
    const stats = {
      totalFiles: 15,
      totalSize: 25 * 1024 * 1024, // 25MB
      typeDistribution: {
        documents: 8,
        images: 5,
        others: 2
      },
      recentUploads: 3
    }
    
    res.json({
      success: true,
      data: stats
    })
  } catch (error) {
    logger.error('Get file stats error:', error)
    res.status(500).json({
      success: false,
      message: error.message || '获取文件统计信息失败'
    })
  }
})

module.exports = router